// 1.引入基础模块
const express = require("express");
const router = express.Router();
const { MongoClient, ObjectId } = require("mongodb");
const DBURL = "mongodb://127.0.0.1:27017";
const dbName = "demo";
const collectionName = "users";

// 创建db对象实例
let dbClient = new MongoClient(DBURL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// 2.连接数据库
const connectDB = () => {
  return new Promise(async (resolve, reject) => {
    try {
      // 连接mongodb服务器
      await dbClient.connect();
      // 连接数据库
      let database = dbClient.db(dbName);
      // 返回数据库连接句柄
      resolve(database);
    } catch (error) {
      reject(error);
    }
  });
};

// 3.添加数据操作
router.get("/useradd", async (req, res) => {
  let { name, age } = req.query;
  let db = await connectDB();
  console.log(db);
  
  try {
    await db.collection(collectionName).insertOne({ name, age });
    res.send({ code: 200, msg: "添加成功" });
  } catch (error) {
    console.log("错误信息：", error);
    res.send({ code: 501, msg: "添加失败" });
  }
});

// 4.修改数据操作
router.get("/useredit", async (req, res) => {
  let { name, age } = req.query;
  let db = await connectDB();
  try {
    let filter = { name };
    let updateDoc = {
      $set: {
        age,
        hopy: "篮球",
      },
    };
    await db.collection(collectionName).updateOne(filter, updateDoc);
    res.send({ code: 200, msg: "修改成功" });
  } catch (error) {
    console.log("错误信息：", error);
    res.send({ code: 501, msg: "修改失败" });
  }
});
// 5.查看数据操作
router.get("/userlist", async (req, res) => {
  let db = await connectDB();
  let query = { age: "20" };
  let options = { _id: 1, name: 1 };
  try {
    let list = await db
      .collection(collectionName)
      .find(query, options)
      .limit(5)
      .sort({ _id: -1 })
      .toArray();
    res.send({ code: 200, msg: "查询成功", data: list });
  } catch (error) {
    console.log("错误信息：", error);
    res.send({ code: 501, msg: "查询失败" });
  }
});
// 6.删除数据操作
router.get("/userremove", async (req, res) => {
  let { name, age } = req.query;
  let db = await connectDB();
  try {
    let filter = { name };
    await db.collection(collectionName).deleteOne(filter);
    res.send({ code: 200, msg: "删除成功" });
  } catch (error) {
    console.log("错误信息：", error);
    res.send({ code: 501, msg: "删除失败" });
  }
});

// 导出路由模块
module.exports = router;
